package com.zhaorui.controller;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.EasyExcel;
import com.zhaorui.entity.ActivityUser;
import com.zhaorui.entity.UserDownLoad;
import com.zhaorui.entity.ZR;
import com.zhaorui.excel.UserDownLoadDataListener;
import com.zhaorui.form.UserQueryForm;
import com.zhaorui.service.ActivityUserService;
import com.zhaorui.service.UserDownLoadService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("/upDown")
@Slf4j
@CrossOrigin
@Api(tags = "Users导入导出接口")
public class UserDownLoadController  implements Serializable {
    @Autowired
    private UserDownLoadService userDownLoadService;
    @Autowired
    private ActivityUserService activityUserService;

    //查询后导出
    @GetMapping("/download")
    @ApiOperation("导出")
    public void download(HttpServletResponse response, UserQueryForm userQueryForm) throws IOException {
        log.info ("开始下载********************");
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType ("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//        response.setContentType ("application/json;charset=utf-8");
        response.setCharacterEncoding ("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode ("activity_user", "UTF-8").replaceAll ("\\+", "%20");
        response.setHeader ("Content-Disposition", "attachment; filename*=UTF-8''" + fileName + ".xlsx");
        UserDownLoad userDownLoad = new UserDownLoad ();
        //复制vo对象接收的参数到DTO对象中
        BeanUtil.copyProperties (userQueryForm, userDownLoad);
        List<UserDownLoad> userDownLoads = userDownLoadService.queryUserDownLoad (userDownLoad);

        EasyExcel.write (response.getOutputStream (), UserDownLoad.class).sheet ("activity_user").doWrite (userDownLoads);
    }


    //批量导入:一定要有监听器：DeptDataListener
    @PostMapping("/upload")
    @ResponseBody
    @ApiOperation("导入有问题")
    public ZR upload(MultipartFile file) throws IOException {
        log.info ("开始导入***********");
        EasyExcel.read (file.getInputStream (), ActivityUser.class, new UserDownLoadDataListener (activityUserService)).sheet ().doRead ();
        System.out.println ("-----");
        return new ZR (1000, "导入成功", null);
    }
}
